package com.supplychain.scm.core.common.version;

import com.supplychain.scm.core.common.annotation.ApiVersion;
import com.supplychain.scm.core.common.version.config.ApiVersionProperties;
import lombok.AllArgsConstructor;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author liyang
 * @version 1.0.0
 * @ClassName ApiVersionRequestMappingHandlerMapping
 * @createTime 12:11:00 2023/01/05
 */
@AllArgsConstructor
public class ApiVersionRequestMappingHandlerMapping extends RequestMappingHandlerMapping {

    private final ApiVersionProperties apiVersionProperties;

    @Override
    protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {
        return getRequestCondition(handlerType.getAnnotation(ApiVersion.class));
    }

    @Override
    protected RequestCondition<?> getCustomMethodCondition(Method method) {
        return getRequestCondition(method.getAnnotation(ApiVersion.class));
    }

    private RequestCondition<?> getRequestCondition(ApiVersion annotation) {
        if (Objects.isNull(annotation)) {
            return null;
        }
        return new ApiVersionRequestCondition(apiVersionProperties, ApiVersionItem.converter(annotation.value(), annotation.clientTypes()));
    }
}
